package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.MallSearchService;
import com.atguigu.gulimall.search.vo.SearchParam;
import com.atguigu.gulimall.search.vo.SearchResult;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service("MallSearchService")
public class MallSearchServiceImpl implements MallSearchService {
    @Resource
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam param) {
        SearchResult searchResult = null;

        //准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            //2.执行检索请求
            SearchResponse search = client.search(searchRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            //3.分析响应数据
            searchResult = buildSearchResult(search,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return searchResult;
    }

    /**
     * 准备检索请求
     * @return
     * @param param
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        /**
         * 查询：模糊匹配，过滤 （按照属性，分类，品牌，价格区间，库存）
         */
        //1.构建bool - query
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if(StringUtils.isNotBlank(param.getKeyword())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("skuTitle",param.getKeyword()));
        }
        //1.2构建 bool - filter  按照三级分类id 查询
        if(param.getCatalog3Id()!=null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId",param.getCatalog3Id()));
        }
        //1.2构建 bool - filter 根据品牌id 查询
        if(param.getBrandId()!=null&&param.getBrandId().size()>0){
            boolQueryBuilder.filter(QueryBuilders.termQuery("brandId",param.getBrandId()));
        }
        // todo 1.2构建 bool - filter 根据所有指定属性 查询

        //1.2构建 bool - filter 按照是否有库存
//        boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock",1==param.getHasStock()));
        //1.2构建 bool - filter 价格区间
        if(StringUtils.isNotBlank(param.getSkuPrice())){
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            String price = param.getSkuPrice();
            if(price.startsWith("_")){
                skuPrice.lte(price.substring(1));
            }else if(price.endsWith("_")){
                skuPrice.gte(price.substring(0,price.length()-1));
            }else {
                String[] s = price.split("_");
                skuPrice.gte(s[0]).lte(s[1]);
            }
            boolQueryBuilder.filter(skuPrice);
        }
        //1.2构建 bool - filter 按照所有指定的属性进行查询
        if(param.getAttrs()!=null&&param.getAttrs().size()>0){
            for (String attr : param.getAttrs()) {
                BoolQueryBuilder nestedBoolQueryBuilder = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];
                String[] attrValues = s[1].split(":");
                nestedBoolQueryBuilder.must(QueryBuilders.termQuery("attrs.attrId",attrId));
                //注意这里有多个value  使用term s Query
                nestedBoolQueryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue",attrValues));
                //每一个必须都得生成一个nested查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQueryBuilder, ScoreMode.None);
                boolQueryBuilder.filter(nestedQuery);
            }
        }


        sourceBuilder.query(boolQueryBuilder);

        /**
         * 排序，分页，高亮
         */
        //2.1排序
        if(StringUtils.isNotBlank(param.getSort())){
            String sort = param.getSort();
            String[] s = sort.split("_");
            SortOrder sortOrder =  s[1].equalsIgnoreCase("asc")?SortOrder.ASC:SortOrder.DESC;
            sourceBuilder.sort(s[0],sortOrder);
        }
        //2.2分页
        sourceBuilder.from((param.getPageNum()-1)*EsConstant.PRODUCT_PAGESIZE);
        sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        //2.3高亮
        if(StringUtils.isNotBlank(param.getKeyword())){
            HighlightBuilder builder = new HighlightBuilder();
            builder.field("skuTitle");
            builder.preTags("<b style='color:red'>");
            builder.postTags("</b>");
            sourceBuilder.highlighter(builder);
        }

        //聚合分析
        //品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId").size(50);
        //品牌聚合的子聚合

        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brandAgg);
        //分类聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg");
        catalogAgg.field("catalogId").size(20);
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalogAgg);
        //属性聚合 attr_agg
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg","attrs");
        // 聚合出当前所有的attrId
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attrAgg.subAggregation(attrIdAgg);
        sourceBuilder.aggregation(attrAgg);

        System.err.println("=====>"+sourceBuilder.toString());
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);

        return searchRequest;
    }

    /**
     * 构建结果数据
     * @param search
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse search,SearchParam param) {
        SearchHits hits = search.getHits();
        SearchResult searchResult = new SearchResult();

        //1.返回的所有查询到的商品
        List<SkuEsModel> esModels = new ArrayList<>();
        SearchHit[] totalHits = hits.getHits();
        if(totalHits!=null&&totalHits.length>0){
            for (SearchHit hit : totalHits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel model = JSON.parseObject(sourceAsString, SkuEsModel.class);
                if(StringUtils.isNotBlank(param.getKeyword())){
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    model.setSkuTitle(string);
                }
                esModels.add(model);
            }
        }
        searchResult.setProducts(esModels);
        Aggregations aggregations = search.getAggregations();

        //2.当前商品所设计到的所有属性信息
        ArrayList<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested attrAgg = aggregations.get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> attrIdAggBuckets = attrIdAgg.getBuckets();
        for (Terms.Bucket attrIdAggBucket : attrIdAggBuckets) {
            long attrId = attrIdAggBucket.getKeyAsNumber().longValue();
            ParsedStringTerms attrNameAgg = attrIdAggBucket.getAggregations().get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            ParsedStringTerms attrValueAgg = attrIdAggBucket.getAggregations().get("attr_value_agg");
            List<String> values = attrValueAgg.getBuckets().stream().map(item -> {
               return  ((Terms.Bucket) item).getKeyAsString();
            }).collect(Collectors.toList());
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo(){
                {
                    setAttrId(attrId);
                    setAttrName(attrName);
                    setAttrValue(values);
                }
            };
            attrVos.add(attrVo);
        }
        searchResult.setAttrVos(attrVos);

        //3.当前商品所涉及到的所有品牌信息
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");
        ArrayList<SearchResult.BrandVo> brandVos = new ArrayList<>();
        List<? extends Terms.Bucket> brandAggBuckets = brandAgg.getBuckets();
        for (Terms.Bucket brandAggBucket : brandAggBuckets) {
            //品牌id
            long brandId = brandAggBucket.getKeyAsNumber().longValue();
            //品牌名字
            ParsedStringTerms brandNameAgg = brandAggBucket.getAggregations().get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            //品牌图片
            ParsedStringTerms brandImgAgg = brandAggBucket.getAggregations().get("brand_img_agg");
            String img = brandImgAgg.getBuckets().get(0).getKeyAsString();
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo(){
                {
                    setBrandId(brandId);
                    setBrandName(brandName);
                    setBrandImg(img);
                }
            };
            brandVos.add(brandVo);
        }

        searchResult.setBrandVos(brandVos);

        //4.当前商品所设计的所有分类信息
        ParsedLongTerms catalogAgg = aggregations.get("catalog_agg");
        List<SearchResult.CatalogVo> catalogVoList = new ArrayList<>();
        List<? extends Terms.Bucket> catalogAggBuckets = catalogAgg.getBuckets();
        for (Terms.Bucket catalogAggBucket : catalogAggBuckets) {
            //从分类聚合中找到catalogId  以及分类名子聚合
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            catalogVo.setCatalogId(catalogAggBucket.getKeyAsNumber().longValue());
            ParsedStringTerms catalogNameAgg = catalogAggBucket.getAggregations().get("catalog_name_agg");
            List<? extends Terms.Bucket> buckets = catalogNameAgg.getBuckets();
            String catalogName = buckets.get(0).getKeyAsString();
            catalogVo.setCatalogName(catalogName);
            catalogVoList.add(catalogVo);
        }
        searchResult.setCatalogVos(catalogVoList);

        //分页信息
        long total = hits.getTotalHits().value;
        searchResult.setPageNum(param.getPageNum());
        searchResult.setTotal(total);
        searchResult.setTotalPages(total%EsConstant.PRODUCT_PAGESIZE==0?total/EsConstant.PRODUCT_PAGESIZE:total/EsConstant.PRODUCT_PAGESIZE+1);
        return searchResult;
    }


}
